import React, { useState, useRef } from 'react'
import {message ,Button,Popconfirm,Divider} from 'antd'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import ProTable from '@ant-design/pro-table'
import { connect} from 'umi'
import { PlusOutlined } from '@ant-design/icons'
import {
  deletePromotion,
  queryPromotionList,
  saveOrUpdatePromotion,
  sendPromotionBpm
} from '../service'
import {approveStatus,jobLevelTypeList} from "@/utils/constant";
import moment from 'moment'
import AddForm from '../components/AddForm'
import store from 'store2';

const TableList = ({currentUser}) => {
  const actionRef = useRef();
  const [visible, setVisible] = useState(false);
  const [loading,setLoading] = useState(false);
  const [record,setRecord] = useState(null);
  const [title,setTitle] = useState(null);

  const addApplication = () =>{
    setVisible(true);
    setTitle('新增管理');
  };

  const handleCancel = () => {
    setVisible(false);
    setRecord(null);
  };

  const edit = (record) => {
    setRecord(record);
    setVisible(true);
    setTitle('编辑管理');
  };

  const delProfession = (id) => {
    setLoading(true);
    deletePromotion(id).then(res => {
      if (res.flag) {
        message.success(`删除成功！`);
        actionRef.current.reload();
      } else {
        message.error(`删除失败，错误:` + res.error);
      }
      setLoading(false);
    })
  };

  const sendBpm = (id) => {
    setLoading(true);
    sendPromotionBpm(id).then(res => {
      setLoading(false);
      message.success(`bpm发起成功！`);
      window.open(res);
    })
  };

  const handleSubmit = (values) => {
    setLoading(true)
    setRecord(null);
    saveOrUpdatePromotion(values).then((res)=> {
      if (res.flag) {
        handleCancel();
        store.remove(`personnel-promotion-manage-` + currentUser.id);
        message.success('管理晋级申请成功！');
        actionRef.current.reload();
      } else {
        message.error(`保存失败，错误:` + res.error);
      }
      setLoading(false)
    }
  )};

  const columns = [
    {
      title: '序号',
      render:(text,record,index)=>`${index+1}`,
      hideInSearch: true,
    },
    {
      title: '工号',
      hideInSearch: true,
      dataIndex: 'code',
      key:'code',
    },
    {
      title: '姓名',
      dataIndex: 'name',
      hideInSearch: true,
      key:'name'
    },
    {
      title: '申请日期',
      dataIndex: 'createTime',
      hideInSearch: true,
      render: (text) => {
        return text != '-' ? moment(text).format('YYYY-MM-DD') : '';
      },
    },
    {
      title: '晋升类型',
      dataIndex: 'promotionType',
      hideInSearch: true,
      render: (text) => {
        const res = jobLevelTypeList.find((item) => item.value === parseInt(text));
        return res ? res.label : text
      },
    },
    {
      title: '所属部门',
      hideInSearch: true,
      dataIndex: 'beforeUnitName',
      key:'beforeUnitName'
    },
    {
      title: '现任岗位',
      dataIndex: 'beforeJobName',
      key:'beforeJobName'
    },
    {
      title: '现职级',
      dataIndex: 'beforeJobLevel',
      hideInSearch: true,
    },
    {
      title: '申请晋升部门',
      dataIndex: 'afterUnitName',
      hideInSearch: true,
    },
    {
      title: '申请晋升岗位',
      dataIndex: 'afterJobName',
      hideInSearch: true,
    },
    {
      title: '申请晋升职级',
      dataIndex: 'afterJobLevel',
      hideInSearch: true,
    },
    {
      title: '申请晋升日期',
      dataIndex: 'promotionDate',
      hideInSearch: true,
      render: (text) => {
        return text != '-' ? moment(text).format('YYYY-MM-DD') : '';
      },
    },
    {
      title: '考察期预计结束日期',
      dataIndex: 'endExpeditionDate',
      hideInSearch: true,
      render: (text) => {
        return text != '-' ? moment(text).format('YYYY-MM-DD') : '';
      },
    },
    {
      title: '考察到期倒计时',
      dataIndex: 'countdown',
      hideInSearch: true,
      render:(text,record) => {
        let ctm = moment();
        let etm = moment(record.endExpeditionDate);
        return etm.diff(ctm, 'days') + "天";
      }
    },
    {
      title: '审批状态',
      dataIndex: 'status',
      key:'status',
      hideInSearch: true,
      valueEnum: {
        1: { text: approveStatus[0].label, status: 'Default' },
        2: { text: approveStatus[1].label, status: 'Processing' },
        3: { text: approveStatus[2].label, status: 'Success' },
        4: { text: approveStatus[3].label, status: 'Default' },
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (item, record) => (
        <>
          {
            (record.status === 1) && <>
              <a onClick={() => edit(record)}>编辑</a>
              <Divider type="vertical"/>
              <Popconfirm title={`是否确认删除?`} onConfirm={() => delProfession(record.promotionId)} okText="是" cancelText="否">
                <a>删除</a>
              </Popconfirm>
              <Divider type="vertical"/>
              <Popconfirm title={`是否确认发起?`} placement="topRight" onConfirm={() => sendBpm(record.promotionId)} okText="是" cancelText="否">
                <a>发起申请</a>
              </Popconfirm>
            </>
          }
          {(record.status !== 1 && record.checkUrl) && <><a onClick={() => window.open(record.checkUrl)}>审批详情</a></>}
        </>
      ),
    }
  ];

  return (
    <PageHeaderWrapper>
      <ProTable
        search={false}
        actionRef={actionRef}
        rowKey="promotionId"
        request={(params) => queryPromotionList(params,2)}
        columns={columns}
        toolBarRender={(action, { selectedRows }) => [
          <Button type="primary" onClick={() => addApplication()}><PlusOutlined/>管理晋级</Button>
        ]}
        options={false}
      />
      <AddForm
        loading={loading}
        visible={visible}
        type={'manage'}
        record={record}
        title={title}
        onCancel={handleCancel}
        onSubmit={handleSubmit}
      />
    </PageHeaderWrapper>
  )
};

export default connect(({user}) => ({
  currentUser: user.currentUser,
}))(TableList)
